Find Sum of Digits of a Number

Theory:

To find the sum of digits of a number, we need to repeatedly extract each digit from the number and add them together.

Python Code:

def sum_of_digits(number):
    sum_digits = 0
    while number > 0:
        digit = number % 10
        sum_digits += digit
        number //= 10
    return sum_digits

# Taking input from the user
number = int(input("Enter a number to find the sum of its digits: "))
print("Sum of digits:", sum_of_digits(number))

Example:

Enter a number to find the sum of its digits: 12345

Sum of digits: 15

Code Explanation:

The function sum_of_digits(number) takes a number as input and returns the sum of its digits.

It iterates through each digit of the number by repeatedly taking the remainder when divided by 10 and then dividing the number by 10. The remainder (digit) is added to the sum, and this process continues until the number becomes zero.

The example usage section demonstrates how to take input from the user, calculate the sum of digits, and print the result.